/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.efounder.chat.fragment;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import androidx.appcompat.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Html;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.chat.R;
import com.efounder.chat.manager.PictureAndCropManager;
import com.efounder.frame.baseui.EFFragment;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.UriUtils;


/**
 * 注册页
 * 
 */
public class RegisterFragment extends EFFragment {
	private static final String TAG = "LoginFragment";
	private View view;
	private RegisterFragmentCallBack callBack;
	
	
    private EditText et_usernick;
    private EditText et_usertel;
    private EditText et_password;
    private Button btn_register;
    private TextView tv_xieyi;
    private ImageView iv_hide;
    private ImageView iv_show;
    private ImageView iv_photo;
    ProgressDialog dialog;

    private String imageName;
    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果

    @Override
    public void onAttach(Activity context) {
    	try {
			callBack = (RegisterFragmentCallBack) context;
		} catch (Exception e) {
			Log.e(TAG, "使用RegisterFragment，必须实现RegisterFragmentCallBack接口");
			e.printStackTrace();
		}
    	super.onAttach(context);
    }
    
    
    @Override
    public View onCreateView(LayoutInflater inflater,
    	 ViewGroup container,  Bundle savedInstanceState) {

        view  = inflater.inflate(R.layout.fragment_register, container, false);
        dialog = new ProgressDialog(getActivity());
        et_usernick = (EditText) view.findViewById(R.id.et_usernick);

        et_usertel = (EditText) view.findViewById(R.id.et_usertel);
        et_password = (EditText) view.findViewById(R.id.et_password);

        // 监听多个输入框
        et_usernick.addTextChangedListener(new TextChange());
        et_usertel.addTextChangedListener(new TextChange());
        et_password.addTextChangedListener(new TextChange());
        btn_register = (Button) view.findViewById(R.id.btn_register);
        tv_xieyi = (TextView) view.findViewById(R.id.tv_xieyi);
        iv_hide = (ImageView) view.findViewById(R.id.iv_hide);

        iv_show = (ImageView) view.findViewById(R.id.iv_show);
        iv_photo = (ImageView) view.findViewById(R.id.iv_photo);
        String xieyi = "<font color=" + "\"" + "#AAAAAA" + "\">" + "点击上面的"
                + "\"" + "注册" + "\"" + "按钮,即表示你同意" + "</font>" + "<u>"
                + "<font color=" + "\"" + "#576B95" + "\">" + "《腾讯微信软件许可及服务协议》"
                + "</font>" + "</u>";

        tv_xieyi.setText(Html.fromHtml(xieyi));
        iv_hide.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_hide.setVisibility(View.GONE);
                iv_show.setVisibility(View.VISIBLE);
                et_password
                        .setTransformationMethod(HideReturnsTransformationMethod
                                .getInstance());
                // 切换后将EditText光标置于末尾
                CharSequence charSequence = et_password.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }

            }

        });
        iv_show.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_show.setVisibility(View.GONE);
                iv_hide.setVisibility(View.VISIBLE);
                et_password
                        .setTransformationMethod(PasswordTransformationMethod
                                .getInstance());
                // 切换后将EditText光标置于末尾
                CharSequence charSequence = et_password.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }
            }

        });
        iv_photo.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showCamera();
            }

        });

        btn_register.setOnClickListener(new OnClickListener() {

            @SuppressLint("SdCardPath")
            @Override
            public void onClick(View v) {

                dialog.setMessage(ResStringUtil.getString(R.string.wrchatview_registering));
                dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                dialog.show();

                String usernick = et_usernick.getText().toString().trim();
                final String password = et_password.getText().toString().trim();
                String usertel = et_usertel.getText().toString().trim();
                Map<String, String> map = new HashMap<String, String>();
                if ((new File("/sdcard/fanxin/" + imageName)).exists()) {
                    map.put("file", "/sdcard/fanxin/" + imageName);
                    map.put("image", imageName);
                } else {
                    map.put("image", "false");
                }
                map.put("usernick", usernick);
                map.put("usertel", usertel);
                map.put("password", password);
                
                new AsyncTask<String, Integer, Integer>() {

					@Override
					protected Integer doInBackground(String... params) {
						try {
							Thread.sleep(1000 *2 );
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						return 1;
					}
					
					@Override
					protected void onPostExecute(Integer result) {
						super.onPostExecute(result);

                        int code = result;
                        if (code == 1) {
                            register("userID", password);
                        } else if (code == 2) {
                            dialog.dismiss();
                            Toast.makeText(getActivity(),
                                    R.string.wechatview_phone_has_been_registered, Toast.LENGTH_SHORT)
                                    .show();
                        } else if (code == 3) {
                            dialog.dismiss();
                            Toast.makeText(getActivity(),
                                    R.string.wechatview_server_registered_fail, Toast.LENGTH_SHORT)
                                    .show();
                        } else if (code == 4) {
                            dialog.dismiss();
                            Toast.makeText(getActivity(),
                                    R.string.wechatview_head_up_fail, Toast.LENGTH_SHORT).show();
                        } else if (code == 5) {
                            dialog.dismiss();
                            Toast.makeText(getActivity(),
                                    R.string.wechatview_return_id_fail, Toast.LENGTH_SHORT)
                                    .show();
                        } else {
                            dialog.dismiss();
                            Toast.makeText(getActivity(),
                                    R.string.wechatview_server_busy, Toast.LENGTH_SHORT)
                                    .show();
                        }

                    
						
					}
					
				}.execute();

            }

        });

    
    	
    	return view;
    }
    

    // 拍照部分
    private void showCamera() {

        final AlertDialog dlg = new AlertDialog.Builder(getActivity()).create();
        dlg.show();
        Window window = dlg.getWindow();
        // *** 主要就是在这里实现这种效果的.
        // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容
        window.setContentView(R.layout.alertdialog);
        // 为确认按钮添加事件,执行退出应用操作
        TextView tv_paizhao = (TextView) window.findViewById(R.id.tv_content1);
        tv_paizhao.setText(R.string.attach_take_pic);
        tv_paizhao.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SdCardPath")
            public void onClick(View v) {

                imageName = getNowTime() + ".png";
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 指定调用相机拍照后照片的储存路径
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        UriUtils.getUriForFile(new File("/sdcard/fanxin/", imageName)));
                startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
                dlg.cancel();
            }
        });
        TextView tv_xiangce = (TextView) window.findViewById(R.id.tv_content2);
        tv_xiangce.setText(R.string.photo_album);
        tv_xiangce.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                getNowTime();
                imageName = getNowTime() + ".png";
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, PHOTO_REQUEST_GALLERY);

                dlg.cancel();
            }
        });

    }

    @SuppressLint("SdCardPath")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
            case PHOTO_REQUEST_TAKEPHOTO:

                new PictureAndCropManager(getActivity()).startPhotoZoom(
                        UriUtils.getUriForFile(new File("/sdcard/fanxin/", imageName)),
                        480);
                break;

            case PHOTO_REQUEST_GALLERY:
                if (data != null)
                    new PictureAndCropManager(getActivity()).startPhotoZoom(data.getData(), 480);
                break;

            case PHOTO_REQUEST_CUT:
//                BitmapFactory.Options options = new BitmapFactory.Options();
//
//                /**
//                 * 最关键在此，把options.inJustDecodeBounds = true;
//                 * 这里再decodeFile()，返回的bitmap为空
//                 * ，但此时调用options.outHeight时，已经包含了图片的高了
//                 */
//                options.inJustDecodeBounds = true;
                Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/fanxin/"
                        +imageName);
                iv_photo.setImageBitmap(bitmap);

                break;

            }
            super.onActivityResult(requestCode, resultCode, data);

        }
    }

    @SuppressLint("SimpleDateFormat")
    private String getNowTime() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("MMddHHmmssSS");
        return dateFormat.format(date);
    }

    // EditText监听器
    class TextChange implements TextWatcher {

        @Override
        public void afterTextChanged(Editable arg0) {

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {

        }

        @Override
        public void onTextChanged(CharSequence cs, int start, int before,
                int count) {

            boolean Sign1 = et_usernick.getText().length() > 0;
            boolean Sign2 = et_usertel.getText().length() > 0;
            boolean Sign3 = et_password.getText().length() > 0;

            if (Sign1 & Sign2 & Sign3) {
                btn_register.setTextColor(0xFFFFFFFF);
                btn_register.setEnabled(true);
            }
            // 在layout文件中，对Button的text属性应预先设置默认值，否则刚打开程序的时候Button是无显示的
            else {
                btn_register.setTextColor(0xFFD0EFC6);
                btn_register.setEnabled(false);
            }
        }

    }

    /**
     * 注册
     * 
     * @param view
     */
    public void register(final String hxid, final String password) {
    	
    	 new AsyncTask<String, Integer, Integer>(){
         	
         	@Override
         	protected Integer doInBackground(String... params) {
         		return 1;
         	}
         	
			protected void onPostExecute(Integer result) {
				dialog.dismiss();
				if (result == 1) {
//					Intent intent = new Intent(getActivity(),
//							MainActivity.class);
//					startActivity(intent);
//					finish();
					callBack.onRegisterSuccess();
				} else {
					Toast.makeText(getActivity(), R.string.wechatview_egistered_fail, Toast.LENGTH_LONG)
							.show();
				}

			}
         	
         	
         }.execute();
    }

    public interface RegisterFragmentCallBack{
    	public void onRegisterSuccess();
    }

}
